package db

import (
	"errors"

	_ "project/study-go/config"
	"project/study-go/logger"

	"github.com/gomodule/redigo/redis"
	"gorm.io/gorm"
)

var (
	//mysql db
	MasterDB *gorm.DB

	//redis
	RedisPool *redis.Pool
)

//ConnDB 连接数据库
func ConnDB() error {
	MasterDB = connMysql()
	err := checkMysql(MasterDB)
	if err != nil {
		return errors.New("mysql server connection unavailable，please check the mysql server or check the config file.")
	}
	logger.RoutineLogger.Infof("connect to Mysql server successfully.")

	RedisPool = connRedis()
	err = checkRedis(RedisPool)
	if err != nil {
		return errors.New("redis server connection unavailable，please check the redis server or check the config file.")
	}
	logger.RoutineLogger.Infof("connect to Redis server successfully.")

	return nil

}

//DisConnDB 关闭数据库
func DisConnDB() error {
	err := closeMysql(MasterDB)
	if err != nil {
		return errors.New(err.Error())
	}
	logger.RoutineLogger.Infof("Close Mysql connections successfully.")

	err = closeRedis(RedisPool)
	if err != nil {
		return errors.New(err.Error())
	}
	logger.RoutineLogger.Infof("Close Redis connections successfully.")

	return err
}
